package cn.kgc.springcloud.controller;

import cn.hutool.core.util.IdUtil;
import cn.kgc.springcloud.entity.Clazz;
import cn.kgc.springcloud.service.ClazzService;
import cn.kgc.springcloud.vo.ClazzVO;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author 课工场
 * @date 2024/10/23
 * @description
 */
@RestController
@RequestMapping("clazzs")
public class ClazzController {

    @Resource
    private ClazzService clazzService;

    @GetMapping
    public List<ClazzVO> clazzList() {

        return clazzService.clazzList();
    }


    @DeleteMapping("{id}")
    public Boolean removeClazz(@PathVariable("id") Integer id) {

        // 删除对应的logo  根据id  查询班级logo文件名称
        String path = clazzService.getById(id).getPath();
        File f = new File("D:/upload/springcloud/" + path);
        if (f.exists()) {
            f.delete();
        }
        // 根据id删除班级信息
        clazzService.removeById(id);

        return true;
    }

    @PostMapping
    public Clazz addClazz(String name, Integer tagId, MultipartFile file) {

        // 文件上传  logo
        String originalFilename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        String uuid = IdUtil.simpleUUID();
        String lastName = uuid + "." + filenameExtension;

        File f = new File("D:/upload/springcloud/" + lastName);

        try {
            file.transferTo(f);
            // 添加班级的基本信息
            Clazz clazz = new Clazz();
            clazz.setPath(lastName);
            clazz.setName(name);
            clazz.setTagid(tagId);
            clazzService.save(clazz);
            return clazz;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("{id}")
    public Clazz getById(@PathVariable("id") Integer id) {

        return clazzService.getById(id);
    }
}
